import React, { Component } from 'react'
import { connect } from 'react-redux'
import { QaAction, QaListAction, ToastAction, QaFooterAction } from '@act'
import { EventCenter, Type, getSeq, getStamp, Data, GUID } from '@utils/Global'
import QuestionEntry from '@com/dm/questionEntry'

class QaFooter extends Component {
  componentDidMount() {
    EventCenter.addListener('focus_footer_input', this.handleFocusAction)
  }
  componentWillUnmount() {
    EventCenter.removeListener('focus_footer_input', this.handleFocusAction)
  }
  handleFocusAction = () => {
    this.input.focus()
  }
  clickQuestionIcon = () => {
    const { qaType, dispatch } = this.props
    const { toggleQaType, setFooterValue } = QaFooterAction
    const { setSelectLinks } = QaAction
    dispatch(toggleQaType(qaType === 'common' ? 'question' : 'common'))
  }
  clickSend = () => {
    const { dispatch, footer_value, select_links, qaType } = this.props
    const { showToast } = ToastAction
    const { insertQa } = QaListAction
    const { setSelectLinks } = QaAction
    const { setFooterValue } = QaFooterAction
    let v = footer_value.replace(/^\s+|\s+$/g, '')
    if (v.length > 150) {
      dispatch(showToast('最多输入150个字', 3 * 1000))
      dispatch(setFooterValue(footer_value.slice(0, 150)))
      return
    }
    if (v === undefined || v === '' || v === null) {
      dispatch(showToast('输入不能为空', 3 * 1000))
      dispatch(setFooterValue(''))
      return
    }
    if (v === 'start') {
      // this.testAutoSend()
    }
    let { local, socket } = qaType === 'common'
      ? this.getLocalQaMsg({ text: footer_value, links: select_links })
      : this.getLocalQuestionMsg({ text: footer_value, links: select_links })

    console.log('local, socket', local, socket)
    const msg = {
      type: Type.COMMON_TYPE.COMMON_QA_TEXT,
      data: {
        text: footer_value,
        links: select_links
      },
      success: () => {},
      fail: () => {}
    }
    dispatch(setFooterValue(''))
    dispatch(insertQa(local))
    dispatch(setSelectLinks([]))
    EventCenter.emit('send_msg_to_socket', socket)
  }
  testAutoSend() {
    let count = 1, timer = null
    timer = setInterval(() => {
      let { local, socket } = this.getLocalQuestionMsg({ text: `这是一条提问${count}`, links: [] })
      EventCenter.emit('send_msg_to_socket', socket)
      count += 1
      if (count > 100) {
        clearInterval(timer)
      }
    }, 300)
  }
  onChange = () => {
    const { setSelectLinks, toggleShowLink } = QaAction
    const { setFooterValue } = QaFooterAction
    const { dispatch, footer_value, select_links } = this.props
    const currentValue = this.input.value
    var replaceValue = ''
    const currentLinks = select_links.concat([])
    if (currentValue.length > 0) {
      if (footer_value.length > currentValue.length) {
        var delete_links = false
        for (var k in currentLinks) {
          var l = currentLinks[k]
          var reg = new RegExp('@' + l.nickname + ' ')
          if (!reg.test(currentValue)) {
            replaceValue = footer_value.replace(reg, '')
            currentLinks.splice(k, 1)
            delete_links = true
            break
          }
        }
        if (delete_links) {
          dispatch(setSelectLinks(currentLinks))
        } else {
          replaceValue = currentValue
        }
      } else {
        var lm = currentValue[currentValue.length - 1]
        if (lm === '@') {
          console.log('222', true)
          dispatch(toggleShowLink(true))
          this.input.blur()
        }
        replaceValue = currentValue
      }
    }
    dispatch(setFooterValue(replaceValue))
  }
  handleSubmit = (e) => {
    if (e.keyCode === 13) {
      e.preventDefault();
      this.clickSend()
    }
  }
  getLocalQaMsg({text, links}) {
    let uuid = GUID.newGUID(30)
    let local = {
      type: Type.COMMON_TYPE.COMMON_QA_TEXT,
      data: { text, links, uuid },
      sender: {
        is_teacher: false,
        nickname: Data.user.nickname,
        headimgurl: Data.user.headimgurl,
        id: Data.user.id
      }
    }
    let socket = {
      type: Type.COMMON_TYPE.COMMON_QA_TEXT,
      data: { text, links, uuid }
    }
    return { local, socket }
  }
  getLocalQuestionMsg({text, links}) {
    let uuid = GUID.newGUID(30)
    let socket = {
      type: Type.COMMON_TYPE.COMMON_QA_QUESTION,
      data: { data: {text, type: 0, links}, uuid }
    }
    let local = {
      type: Type.COMMON_TYPE.COMMON_QA_QUESTION,
      sender: {
        is_teacher: false,
        nickname: Data.user.nickname,
        headimgurl: Data.user.headimgurl,
        id: Data.user.id
      },
      data: {
        question: {
          id: 0,
          data: { type: 0, text, links },
          up_num: 0,
          user_id: Data.user.ID,
          like: false,
          users: [],
          user: {id: Data.user.id, nickname: Data.user.nickname, name: Data.user.nickname, headimgurl: Data.user.headimgurl},
        },
        question_id: 0,
        uuid
      }
    }
    return { local, socket }
  }
  render() {
    const { footer_value, color_theme, qaType } = this.props
    const placeholder = qaType === 'common' ? '说点什么吧...' : '发送为提问'
    const _className = color_theme === 'red' ? 'qa_footer red' : 'qa_footer'
    let questionIcon = require(`@images/question/live_footer${qaType === 'common' ? '_no' : ''}_question_icon.png`)
    return (
      <div className={_className}>
        <div className="input_con">
          <textarea
            ref={r => this.input = r}
            onChange={this.onChange}
            value={footer_value}
            className="input"
            type="text"
            placeholder={placeholder}
            onKeyDown={this.handleSubmit}
          />
        </div>
        <div className="send_btn_con">
          <QuestionEntry type="qa"/>
          <div onClick={this.clickQuestionIcon} className={`toggle_question_icon ${qaType === 'common' ? '' : 'active'}`}>
            <img className="question_icon" src={questionIcon} alt=""/>
            发送为提问
          </div>
          <div className="send_btn" onClick={this.clickSend}>发送</div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    color_theme: state.MainScreenState.info.color_theme,
    footer_value: state.QaFooterState.footer_value,
    select_links: state.QaState.select_links,
    qaType: state.QaFooterState.qaType
  }
}

export default connect(mapStateToProps)(QaFooter)
